function setCookie(cname, cvalue, exdays) {
    const d = new Date();
    d.setTime(d.getTime() + (exdays * 24 * 60 * 60 * 1000));
    const expires = "expires=" + d.toUTCString();
    document.cookie = cname + "=" + cvalue + ";" + expires + ";path=/";
}

function getCookie(cname) {
    const name = cname + "=";
    const decodedCookie = decodeURIComponent(document.cookie);
    const ca = decodedCookie.split(';');
    for (let i = 0; i < ca.length; i++) {
        var c = ca[i];
        while (c.charAt(0) == ' ') {
            c = c.substring(1);
        }
        if (c.indexOf(name) == 0) {
            return c.substring(name.length, c.length);
        }
    }
    return "";
}

var app = angular.module('deepDRapp', ['ngRoute', 'ngFileUpload', 'smart-table', 'AngularPrint']);
// Define the `PhoneListController` controller on the `phonecatApp` module
app.controller('appController', ['$scope', 'Upload', '$timeout', '$http',
    function appController($scope, Upload, $timeout, $http) {
    $scope.name = 'default name2';
    $scope.menuItem = 'index';
    $scope.debug = false;
    $scope.token = '';
    $scope.LogedIn = false;
    $scope.set_token = function (token) {
        $scope.token = token;
        setCookie('token', token, 7);
        setCookie('name', $scope.usrname, 7)
    };
    $scope.set_menu_item = function (manu_item, callback=null) {
        // if($scope.token ===''){
        //     $scope.menuItem = 'login';
        //     return
        // }
        $scope.menuItem = manu_item;
        console.log(callback);
        if (callback!==null){
            callback();
        }
    };
    $scope.exit_login = function(){
        $scope.token = "";
        $scope.LogedIn = false;
        setCookie('token',"",0);
        setCookie('name','',0);
    };
    $scope.login = function () {
        $http({
            method: 'POST',
            url: '/api/get_token',
            headers: {
                'Content-Type': 'application/json'
            },
            data: {
                'name': $scope.usrname,
                'psw': $scope.psw
            }
        }).then(function (response) {
            // success call back
            console.log('successful request');
            console.log(JSON.stringify(response.data));
            if (response.data['token'] !== '') {
                $scope.set_token(response.data['token']);
                succ = true;
                $scope.LogedIn = true;
                alert("LogedIn successfully!")
            } else {
                console.log(response.data)
            }
        }, function (response) {
            alert("Login Error! Please check user name and password!");
            console.log(response)
        });

    };
    $scope.init = function () {
        console.log('init');
        var token =  getCookie('token');
        $scope.usrname = getCookie('name');
        if (token !== ""){
            $scope.token = token;
            $scope.LogedIn = true;
        }
        if($scope.LogedIn){
            $http({
                method: 'GET',
                url: '/api/get_user_profile',
                headers: {
                    'Content-Type': 'application/json',
                    'token': $scope.token
                }
            }).then(function (response) {
                $scope.title = response.data.inditude;
            }, function (response) {
                alert("Login Error !");
                console.log(response)
            });        
        }
        $scope.set_menu_item('start')
    }
}]);

/**
 * pictures are structures like this:
 * {
 *      url : set when finished
 *      id : set when finished
 *      percentage:
 *      which_eye: right/left
 * }
 */
app.controller('newImage', ['$scope', 'Upload', '$timeout', '$http','$window',
    function ($scope, Upload, $timeout, $http, $window) {
        $scope.init = function () {
            $scope.patient = {
                name: null,
                gender: 'male',
                age: null,
                eye_sight: null,
                id: 0,
                pictures: [],
                reports_ready: true,
                submitted: false,
                diag_finished: false,
                lgrade: -1,
                rgrade: -1,

                addpic: function (file) {
                    var x = {
                        // server returned info
                        url: '',
                        id: 0,
                        // file info
                        which_eye: 'right',
                        file: file,
                        // upload info
                        percentage: 0,
                        finished: false,
                        error: false,
                        started: false,
                        filename: '',
                        result: {
                            ready: false
                        }
                    };

                    this.pictures.push(x);
                },
            };
            $scope.refreshIntervalId = 1;
            $scope.diagnose_nready = true;
            $scope.degreemap = {};
            $scope.degreemap[0] = 'No obvious DR';
            $scope.degreemap[1] = 'mild NPDR';
            $scope.degreemap[2] = 'moderate NPDR';
            $scope.degreemap[3] = 'severe NPDR';
            $scope.degreemap[4] = 'PDR';
            $scope.degreemap['无图片'] = 'No Image';
            $scope.degreemap[-1] = 'No Image';

            $scope.gendermap = {};
            $scope.gendermap['male'] = 'male';
            $scope.gendermap['female'] = 'male';

        };
        $scope.init();
        $scope.getPositionDescp = function (lessions) {
            if (lessions.length == 0) {
                return '';
            }
            rr = {};
            for (var i = 0; i < lessions.length; i++) {
                if (rr[lessions[i].type] === undefined) {
                    rr[lessions[i].type] = []
                }
                rr[lessions[i].type].push(lessions[i].position)
            }
            retstr = 'These lesions can be observed in fundus image:';
            for (var lession in rr) {
                for (v of rr[lession]) {
                    retstr += 'at ' + v + ':'
                }
                retstr = retstr.slice(0, retstr.length - 1) + lession + ';';
            }
            return retstr;
        };
        $scope.getSuggStr = function () {
            var m = 0;
            for (var i = 0; i < $scope.patient.pictures.length; i++) {
                if (m < $scope.patient.pictures[i].result.level) {
                    m = $scope.patient.pictures[i].result.level
                }
            }
            const strs = [
              'regularly follow up examination',
              'regularly follow up examination',
              'further ophthalmologic examination id needed',
              'further ophthalmologic examination id needed',
              'further ophthalmologic examination id needed',
            ];
            return strs[m];
        };
        $scope.showPrintBtn = true;
        $scope.print_report = function () {
            function sleep(ms) {
                return new Promise(resolve => setTimeout(resolve, ms));
            }

            $scope.showPrintBtn = false;
            sleep(500).then(() => {
                window.print()
            });
        };
        $scope.get_report = function () {
            console.log('fuck');
            $scope.set_menu_item('report');
            // var sum = 0;

            // for (var i = 0; i < $scope.patient.pictures.length; i++) {
            //     sum += $scope.patient.pictures[i].result.level;
            // }
            // sum /= $scope.patient.pictures.length;
            // for (var i = 0; i < $scope.patient.pictures.length; i++) {
            //     $scope.patient.pictures[i].result.level = sum;
            // }

        };
        $scope.review_report = function (patient_id) {
            console.log('get report', patient_id);
            $http({
                method: 'GET',
                url: '/api/get_report/' + patient_id,
                headers:{"token": $scope.token}
            }).then(function (response) {
                // success call back
                console.log('successful request');
                console.log(response.data);
                $scope.report_review_data = response.data;
                // $scope.$apply('$scope.patient');
            }, function (response) {
                console.error(response)
            });
        };
        $scope.$watch('report_review_data', function () {
            if($scope.report_review_data==null) {
                return
            }
            console.log('reports_review change');
            console.log($scope.report_review_data);
            // $scope.patient = $scope.report_review_data.patient;
            // $scope.patient.pictures = [];
            $scope.patient.name = $scope.report_review_data.patient.name;
            $scope.patient.gender = $scope.report_review_data.patient.gender;
            $scope.patient.age = $scope.report_review_data.patient.age;
            $scope.patient.eye_sight = $scope.report_review_data.patient.eye_sight;
            $scope.patient.id = $scope.report_review_data.patient.id;
            $scope.patient.pictures.length = 0;
            for(var i = 0; i < $scope.report_review_data.pictures.length;i++){
                $scope.patient.pictures.push($scope.report_review_data.pictures[i]);
            }
            if ($scope.patient) {
                for (var i = 0; i < $scope.patient.pictures.length; i++) {
                    var ttmp = $scope.patient.pictures[i];
                    if (ttmp.which_eye == "right") {
                        if ($scope.patient.rgrade < ttmp.result.level || $scope.patient.rgrade == '无图片') {
                            $scope.patient.rgrade = ttmp.result.level
                        }
                    } else {
                        if ($scope.patient.lgrade < ttmp.result.level || $scope.patient.lgrade == '无图片') {
                            $scope.patient.lgrade = ttmp.result.level
                        }
                    }
                }
            }
            // console.log($scope.getPositionDescp());
            console.log($scope.patient);
            $timeout(function() {
                console.log("TIME OUT");
                $scope.$apply();
                $scope.get_report();
            }, 10);
            // $scope.$apply();
            // file.result.positionDescp = $scope.getPositionDescp($scope.report_review_data.result.lesion);
        });

        $scope.get_diagnose_result = function (file) {
            if (file.result && file.result.ready) {
                return true
            }
            console.log('get result for ' + file.id);
            if (!file.id || file.id <= 0) {
                return false
            }
            $http({
                method: 'GET',
                url: '/api/get_single_image_eng/' + file.id,
                headers:{"token": $scope.token}
            }).then(function (response) {
                // success call back
                console.log('successful request');
                console.log(response);
                file.result = response.data.result;
                file.result.ready = response.data.result.ready;
                // file.patient = response.data.patient
                file.filename = response.data.filename;
                if (response.data.which_eye == "right") {
                    if ($scope.patient.rgrade < response.data.result.level || $scope.patient.rgrade == '无图片') {
                        $scope.patient.rgrade = response.data.result.level
                    }
                } else {
                    if ($scope.patient.lgrade < response.data.result.level || $scope.patient.lgrade == '无图片') {
                        $scope.patient.lgrade = response.data.result.level
                    }
                }
                console.log($scope.getPositionDescp(response.data.result.lesion));
                file.result.positionDescp = $scope.getPositionDescp(response.data.result.lesion);
            }, function (response) {
                console.error(response)
            });
        };
        // $scope.performUpload = function (index) {
        //     $scope.upload($scope.patient.pictures[index])
        // }
        $scope.delPic = function (index) {
            if (index > $scope.patient.pictures.length || index < 0) {
                console.error('Error insex of ' + index);
                return;
            }
            console.log('deleting ' + index + 'th picture');
            $scope.patient.pictures.splice(index, 1);
        };
        $scope.diagnoseReady = function () {
            console.log("Finished!!!!");
            $scope.diagnose_nready = false;
            console.log($scope.patient);
            alert('Diagnose finished!')
        };
        $scope.new_patient = function () {
            if(!$scope.LogedIn) {
                alert("Please login first");
                return
            }
            console.log('add patient');
            const uploadPatient = function () {
                $http({
                    method: 'POST',
                    url: '/api/add_patient',
                    headers: {
                        'Content-Type': 'application/json',
                        "token": $scope.token
                    },
                    data: $scope.patient
                }).then(function (response) {
                    // success call back
                    console.log('successful request');
                    console.log(response);
                    $scope.patient.id = response.data.id;
                    $scope.patient.created_date = response.data.created_date;
                }, function (response) {
                    console.log(response)
                });
                $scope.submitted = true;
                // start watch function
                $scope.refreshIntervalId = setInterval(function () {
                    var r = false;
                    for (var i = 0; i < $scope.patient.pictures.length; i++) {
                        r = r || !$scope.get_diagnose_result($scope.patient.pictures[i]);
                    }
                    if (!r) {
                        $scope.diagnoseReady();
                        clearInterval($scope.refreshIntervalId);
                    }
                }, 2000)
            };
            $scope.uploadAllPic(uploadPatient);
        };
        $scope.$watch('files', function () {
            console.log('files change');
            if (!$scope.files) {
                return
            }
            for (var i = 0; i < $scope.files.length; i++) {
                $scope.patient.addpic($scope.files[i]);
            }
        });
        $scope.log = '';

        $scope.upload = function (index, callback) {
            f = $scope.patient.pictures[index];
            if (!f || f.started || f.finished || !f.file) {
                console.error('error when trying to upload ' + f);
                return;
            }
            console.info('uploading file ' + f.file.name);
            f.started = true;
            var file = f.file;
            if (!file.$error) {
                Upload.upload({
                    url: '/api/upload',
                    headers:{"token": $scope.token},
                    data: f
                }).then(function (resp) {
                    console.log("Succ Upload", resp);
                    $timeout(function () {
                        $scope.log = 'file: ' +
                            resp.config.data.file.name +
                            ', Response: ' + JSON.stringify(resp.data) +
                            '\n' + $scope.log;
                        f.id = resp.data.id;
                        f.url = resp.data.url;
                        f.finished = true;
                        index += 1;
                        if (index < $scope.patient.pictures.length) {
                            $scope.upload(index, callback)
                        } else {
                            callback();
                        }
                    });
                }, null, function (evt) {
                    f.percentage = parseInt(100.0 * evt.loaded / evt.total);
                });
            }
        };
        $scope.uploadAllPic = function (afterCallBack) {
            $scope.upload(0, afterCallBack);
        };
        $scope.update_change = function () {
            alert('修改已提交')
        };

        // List related funcs
        $scope.rowCollection = [];
        $scope.renew = function () {
            if(!$scope.LogedIn){
                alert("请先登录！");
                return
            }
            console.log('updata');
            $http({
                method: 'GET',
                url: '/api/get_image_list',
                headers: {"token": $scope.token},
            }).then(function (response) {
                // success call back
                console.log('successful request');
                console.log(response);
                $scope.rowCollection = response.data;
                // if (recall_func) {
                //     recall_func(response.data);
                // }
            }, function (response) {
                console.log(response)
            });
        };
        $scope.reset_content = function () {
            // $scope.init();
            // $scope.set_menu_item('start');
            $window.location.reload()
        }
    }]);

app.controller('deepmarker', ['$scope', '$timeout', '$http', function (scope, $timeout, $http) {
    scope.vals = {
        "HTN treatment": "1",
        "B_CPTIDE": "1.43",
        "trend": "-1.2",
        "HDL-c": "1.465",
        "B_APO_A1": "1.47994",
        "B_CK": "26.5",
        "priorcvd": "0",
        "total cholesterol": "5.335",
        "heart rate": "73.3333333333",
        "creatinine": "73",
        "trt_code": "0",
        "all_sum": "160",
        "BMI": "35.07",
        "hsCRP": "3.18",
        "B_AP": "165",
        "hip": "123",
        "fasting insulin": "13",
        "fasting plasma glucose": "9.8",
        "HbA1c": "7.65",
        "B_APO_B": "1.04",
        "B_FIBG": "3.875",
        "LDL-c": "3.18",
        "B_APO_A2": "0.31",
        "B_BILI": "6",
        "SBP": "153.333333333",
        "waist": "109",
        "B_ALT": "51.5",
        "ever smoker": "0",
        "age": "65",
        "triglyceride": "1.52",
        "race": "1",
        "b_fgf21": "294.11",
        "B_GGT": "29",
        "DBP": "92.6666666667",
        "male": "0",
        "B_LP_A": "222"
    };
    scope.res = null;
    scope.getResp = function (r) {
        scope.res = r;
        console.log('setting to', r);
    };
    scope.submit = function (recall_func) {
        scope.sendvars(scope.getResp)
    };
    scope.sendvars = function (recall_func) {
        console.log('updata');
        $http({
            method: 'POST',
            url: '/1.0/dp/mark',
            headers: {
                'Content-Type': 'application/json'
            },
            data: scope.vals
        }).then(function (response) {
            // success call back
            console.log('successful request');
            console.log(response.data);
            if (recall_func) {
                recall_func(response.data)
            }
            // $scope.init();
        }, function (response) {
            console.log(response)
        });
    };

}]);

app.controller('image_list', ['$scope', '$timeout', '$http', function (scope, $timeout, $http) {
    scope.rowCollection = [];
    scope.confirmed = 0;
    scope.class_confirmed = 'active';
    scope.class_unconfirmed = '';
    scope.page_num = 1;
    scope.degree_desp = {0: '无病变', 1: '疑似病变', 2: '有病变', 1000: '眼科就诊详查'};
    scope.level_desp = {0: '未见DR', 1: '轻度NPDR', 2: '中度NPDR', 3: '重度NPDR', 4: 'PDR', 1000: '无法诊断'};
    scope.none_dr_lesion_desp = ['无', 'AMD', '视盘病变', 'RVO', 'PM', 'EMR', '其他'];
    scope.quality_desp = {0: '良好', 1: '影响诊断', 2: '无法诊断', 3: '有伪影'};
    scope.items_per_page = 10;
    scope.max_page = 1;

    // scope.renew = function (recall_func) {
    //     console.log('updata', scope.confirmed);
    //     scope.get_max_page();
    //     if (scope.page_num > scope.max_page) {
    //         scope.page_num = scope.max_page;
    //     }
    //     $http({
    //         method: 'GET',
    //         url: '/api/check_list/' + scope.confirmed + '/' + scope.page_num + '/' + scope.items_per_page,
    //     }).then(function (response) {
    //         // success call back
    //         console.log('successful request');
    //         console.log(response);
    //         scope.rowCollection = response.data;
    //         if (recall_func) {
    //             recall_func(response.data);
    //         }
    //     }, function (response) {
    //         // err response
    //         console.log(response)
    //     });
    // };
    scope.change_degree = function (index, level) {
        console.log(index + ' change to ' + level);
        if (level == scope.rowCollection[index].degree) {
            return
        }
        scope.rowCollection[index].degree = level;
        scope.rowCollection[index].changed = 1;
    };
    scope.change_level = function (index, level) {
        console.log(index + ' change to ' + level);
        if (level == scope.rowCollection[index].level) {
            return
        }
        scope.rowCollection[index].level = level;
        scope.rowCollection[index].changed = 1;
    };
    scope.change_quality = function (index, level) {
        console.log(index + ' change to ' + level);
        if (level == 2) {
            scope.change_level(index, 1000);
            scope.change_degree(index, 1000)
        }
        if (level == scope.rowCollection[index].image_quality) {
            return
        }
        scope.rowCollection[index].image_quality = level;
    };
    scope.change_none_dr = function (index, value) {
        scope.rowCollection[index].none_dr_lesion = value;
    };
    scope.confirm_result = function () {
        $http({
            method: 'POST',
            url: '/api/confirm',
            headers: {
                'Content-Type': 'application/json'
            },
            data: scope.rowCollection
        }).then(function (response) {
            // success call back
            console.log('successful request');
            console.log(response);
            alert('提交成功');
            scope.renew();
            // $scope.init();
        }, function (response) {
            console.log(response);
            alert('提交失败');
            scope.renew();
        });
    };
    scope.get_max_page = function () {
        $http({
            method: 'GET',
            url: '/api/check_list/count/' + scope.confirmed,
            headers: {
                'Content-Type': 'application/json'
            },
            data: scope.rowCollection
        }).then(function (response) {
            // success call back
            console.log('successful request');
            console.log(response);
            scope.max_page = Math.ceil(response.data.count / scope.items_per_page);
        }, function (response) {
            console.error(response);
            alert('提交失败');
            scope.renew();
        });
    };
    scope.next_page = function () {
        console.log('next');
        scope.page_num += 1;
        scope.renew(function (data) {
            if (data.length <= 0) {
                scope.page_num -= 1;
            }
        });
    };
    scope.prev_page = function () {
        console.log('prev');
        if (scope.page_num > 1) {
            scope.page_num -= 1;
        } else {
            alert("已经到第一页");
            return
        }
        scope.renew();
    };
    scope.renew();


}]);

app.controller('login', ['$scope', '$timeout', '$http', function (scope, $timeout, $http) {
    scope.user_name = '';
    scope.psw = '';
    scope.login = function () {
        $http({
            method: 'POST',
            url: '/api/get_token',
            headers: {
                'Content-Type': 'application/json'
            },
            data: {
                'user_name': scope.user_name,
                'password': scope.psw
            }
        }).then(function (response) {
            // success call back
            console.log('successful request');
            console.log(JSON.stringify(response.data));
            if (response.data['token'] !== '') {
                scope.set_token(response.data['token']);
                scope.set_menu_item('index');
            } else {
                alert(response.data['error'])
            }
        }, function (response) {
            console.log(response)
        });
    };

}]);
